package com.jnu.ilearn;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.jnu.ilearn.bean.DataBank;
import com.jnu.ilearn.bean.Seat;
import com.jnu.ilearn.bean.SeatItem;
import com.jnu.ilearn.bean.User;
import com.jnu.ilearn.utils.DBUtils;
import com.jnu.ilearn.utils.DataLoader;
import com.jnu.ilearn.utils.SeatUtils;
import com.jnu.ilearn.utils.UserUtils;

import java.sql.Connection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LoginActivity extends AppCompatActivity {
    boolean account_pr=true,passwordVisibility=false;
    boolean style_valid=false;//用于判断目前所输入的账号是否合格
    EditText passwordText,accountText;
    User loginUser;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getSupportActionBar().hide();
        init();
    }


    void init(){
        DataBank dataBank=new DataBank(LoginActivity.this);
        dataBank.loadData();
        User user=dataBank.getUser();
        if(!user.getAccount().equals("account")){
            Intent intent=new Intent(LoginActivity.this,MainActivity.class);
            loginUser=user;
            intent.putExtra("User",loginUser);
            startActivity(intent);
            finish();
        }
        accountText=findViewById(R.id.account_input);
        passwordText=findViewById(R.id.password_input);
        ImageView imageView=findViewById(R.id.password_visibility);
        imageView.setOnClickListener(new MyListener());
        accountText.setOnFocusChangeListener(new View.OnFocusChangeListener(){
            @Override
            //判断所输入账号是否符合格式，以此显示不同照片
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    account_pr=false;//确认点击之后才会显示出判断对错的图片
                }
                else{
                    if(!account_pr){
                        String account=accountText.getText().toString();
                        String Regex="^[0-9a-z]+\\w*@([0-9a-z]+\\.)+[0-9a-z]+$";
                        Pattern compile = Pattern.compile(Regex);
                        Matcher matcher = compile.matcher(account);
                        style_valid=matcher.matches()&&account.length()<=20;
                        if(style_valid){
                            ImageView imageView=findViewById(R.id.account_style);
                            imageView.setVisibility(View.VISIBLE);
                            imageView.setImageResource(R.drawable.style_ture);
                        }
                        else{
                            ImageView imageView=findViewById(R.id.account_style);
                            imageView.setVisibility(View.VISIBLE);
                            imageView.setImageResource(R.drawable.style_false);
                        }
                    }
                }
            }
        });
        TextView submit=findViewById(R.id.btn_submit);
        submit.setOnClickListener(new MyListener());
        TextView register=findViewById(R.id.btn_register);
        register.setOnClickListener(new MyListener());
    }
    ActivityResultLauncher<Intent> launcherRegister = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>(){
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data=result.getData();
            int resultCode = result.getResultCode();
            if(resultCode==1)
            {
                String account=data.getStringExtra("account");
                String password=data.getStringExtra("password");
                String kind=data.getStringExtra("kind");
                accountText.setText(account);
                passwordText.setText(password);
                if(kind.equals("student")){
                    RadioButton btn_student=findViewById(R.id.account_student);
                    btn_student.setChecked(true);
                }
                else{
                    RadioButton btn_manager=findViewById(R.id.account_manager);
                    btn_manager.setChecked(true);
                }

                Toast.makeText(LoginActivity.this,"注册成功",Toast.LENGTH_LONG).show();
            }

        }
    });
    class MyListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.password_visibility:
                    //输入密码是否可见
                    if(!passwordVisibility){
                        passwordVisibility=true;
                        ImageView imageView=(ImageView)v;
                        imageView.setImageResource(R.drawable.password_visible);
                        passwordText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    }
                    else{
                        passwordVisibility=false;
                        ImageView imageView=(ImageView)v;
                        imageView.setImageResource(R.drawable.password_invisible);
                        passwordText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    }
                    break;
                case R.id.btn_submit:
                    //提交按钮逻辑写在此处
                    AlertDialog.Builder builder=new AlertDialog.Builder(LoginActivity.this);
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() //确认框，点击确定传回数据给主界面
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                           Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                           intent.putExtra("User",loginUser);
                            DataBank dataBank=new DataBank(LoginActivity.this);
                            dataBank.loadData();
                            User user=dataBank.getUser();
                            user.setAccount(loginUser.getAccount());
                            user.setAlias(loginUser.getAlias());
                            user.setPassword(loginUser.getPassword());
                            user.setIdentity(loginUser.getIdentity());
                            user.setPoint(loginUser.getPoint());
                            dataBank.saveData();
                           startActivity(intent);
                        }
                    });

                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

                    DataLoader dataLoader=new DataLoader();
                    Handler handler=new Handler(Looper.getMainLooper()){
                        @Override
                        public void handleMessage(@NonNull Message msg) {
                            super.handleMessage(msg);
                            List<User> users=dataLoader.GetUser();
                            String Account=accountText.getText().toString();
                            String Password=passwordText.getText().toString();
                            boolean account_exit=false;
                            boolean password_false=true;
                            boolean kind_false=true;
                            String Regex="^[0-9a-z]+\\w*@([0-9a-z]+\\.)+[0-9a-z]+$";
                            Pattern compile = Pattern.compile(Regex);
                            Matcher matcher = compile.matcher(Account);
                            RadioButton btn_student=findViewById(R.id.account_student);
                            String kind="manager";
                            if(btn_student.isChecked())
                                kind="student";

                            for (User user : users) {
                                if(Account.equals(user.getAccount())){
                                    account_exit=true;
                                    if(Password.equals(user.getPassword())){
                                        password_false=false;
                                    }
                                    if(kind.equals(user.getIdentity())){
                                        kind_false=false;
                                    }
                                    if(account_exit&&!password_false&&!kind_false){
                                        loginUser=user;
                                    }
                                    break;
                                }
                            }

                            if(!matcher.matches()){
                                new AlertDialog.Builder(LoginActivity.this).setTitle("警告").setMessage("账号格式不正确").show();
                            }
                            else if(Account.length()>20){
                                new AlertDialog.Builder(LoginActivity.this).setTitle("警告").setMessage("账号字符不得多于20位").show();
                            }
                            else if(!account_exit){
                                new AlertDialog.Builder(LoginActivity.this).setTitle("警告").setMessage("账号错误").show();
                            }
                            else if(password_false){
                                new AlertDialog.Builder(LoginActivity.this).setTitle("警告").setMessage("密码错误").show();
                            }
                            else if(kind_false){
                                new AlertDialog.Builder(LoginActivity.this).setTitle("警告").setMessage("权限选择错误").show();
                            }
                            else{
                                //将确认框显示出来
                                builder.setMessage("是否确定登录");
                                builder.setTitle("提示");
                                builder.show();
                            }
                        }
                    };
                    dataLoader.LoadUser(handler);

                    break;
                case R.id.btn_register:
                    Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
                    launcherRegister.launch(intent);


            }
        }
    }
}